package com.company.project.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

public class FileDownload
{

	private final static String DEFAULT_PATH = "D:/cache/temp/";

	public static void main(String[] args)
	{
		String downloadUrl = "http://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511954550380&di=59c702799bffe9585e9a3ebbef75d037&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2Fcc11728b4710b912339b00e7c9fdfc0392452255.jpg";
		String resourceName = "" + System.currentTimeMillis();
		downloadUrlFile(downloadUrl, null, resourceName);
	}

	/**
	 * 文件下载springmvc封装，只适合小文件下载
	 * 
	 * @param filePath
	 * @return demo:
	 * @RequestMapping(value = "/downloadFile") public ResponseEntity<byte[]>
	 *                       downloadFile( HttpServletRequest request) { String
	 *                       filePath =
	 *                       "D:/download/baiduyundownload/FileServerSSM.rar";
	 *                       ResponseEntity<byte[]> entity =
	 *                       FileDownload.fileDownload2(filePath); return
	 *                       entity; }
	 */
	public static ResponseEntity<byte[]> fileDownload2(String filePath)
	{
		System.out.println("filePath:" + filePath);
		File file = new File(filePath);
		ResponseEntity<byte[]> entity = null;
		try
		{
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Disposition", "attchement;filename=" + file.getName());
			HttpStatus statusCode = HttpStatus.OK;
			entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, statusCode);

		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return entity;
	}

	/**
	 * 文件下载
	 * 
	 * @param response
	 * @param filePath
	 * @throws IOException
	 *             demo:
	 * @RequestMapping(value = "/downloadFile")
	 * @ResponseBody public void downLoadFile(HttpServletResponse response) {
	 *               String filePath =
	 *               "D:/download/baiduyundownload/FileServerSSM.rar"; try {
	 *               FileDownload.fileDownload(response, filePath); } catch
	 *               (IOException e) { e.printStackTrace(); } }
	 * 
	 * 
	 */
	public static void fileDownload(HttpServletResponse response, String filePath) throws IOException
	{
		File file = new File(filePath);
		OutputStream out = null;
		InputStream in = null;
		System.out.println("filePath:" + filePath);
		try
		{
			in = new FileInputStream(file);
			response.reset();
			response.setHeader("Content-Length", "" + file.length());
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
			out = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf, 0, 1024)) != -1)
			{
				out.write(buf, 0, len);
			}

		} finally
		{
			if (in != null)
			{
				try
				{
					in.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			if (out != null)
			{
				try
				{
					out.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 *
	 * @param downloadUrl
	 *            下载的路径
	 * @param destinationPath
	 *            文件存储的绝对路径
	 * @param resourceName
	 *            最終的文件名
	 * 
	 * @return info , if result is null is failed
	 */
	public static FileInfo downloadUrlFile(String downloadUrl, String destinationPath, String resourceName)
	{
		FileInfo fileInfo = null;
		try
		{
			URL url = new URL(downloadUrl);

			// 打开链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置请求方式为"GET"
			conn.setRequestMethod("GET");
			// 超时响应时间为5秒
			conn.setConnectTimeout(5 * 1000);
			// 通过输入流获取图片数据
			InputStream in = conn.getInputStream();

			String contentType = conn.getHeaderField("Content-Type");
			System.out.println("contentType:" + contentType);
			if (destinationPath == null || destinationPath.length() == 0)
				destinationPath = DEFAULT_PATH;
			String fileType = getFileTypeByContentType(contentType);
			String filePath = destinationPath + File.separator + resourceName + "." + fileType;

			FileUtils.copyInputStreamToFile(in, new File(filePath));
			File file = new File(filePath);
			fileInfo = new FileInfo();
			fileInfo.setSimpleName(file.getName());
			fileInfo.setFileName(file.getName());
			fileInfo.setResourceName(file.getName());
			fileInfo.setFileType(fileType);
			fileInfo.setFilePath(filePath);
			System.out.println("fileInfo:" + JSON.toJSONString(fileInfo));
			return fileInfo;

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static class FileInfo
	{
		// 只有文件名
		String simpleName;
		// 原文件名
		String fileName;
		// 文件最终的资源名
		String resourceName;
		// 文件最终存储的全路径
		String filePath;
		// 文件类型
		String fileType;

		@Override
		public String toString()
		{
			return ToStringBuilder.reflectionToString(this);
		}

		public String getResourceName()
		{
			return resourceName;
		}

		public void setResourceName(String resourceName)
		{
			this.resourceName = resourceName;
		}

		public String getSimpleName()
		{
			return simpleName;
		}

		public void setSimpleName(String simpleName)
		{
			this.simpleName = simpleName;
		}

		public String getFileName()
		{
			return fileName;
		}

		public void setFileName(String fileName)
		{
			this.fileName = fileName;
		}

		public String getFilePath()
		{
			return filePath;
		}

		public void setFilePath(String filePath)
		{
			this.filePath = filePath;
		}

		public String getFileType()
		{
			return fileType;
		}

		public void setFileType(String fileType)
		{
			this.fileType = fileType;
		}

	}

	private static String getFileTypeByContentType(String contentType)
	{
		switch (contentType)
		{
		case "image/jpeg":
			return "jpg";
		}
		return "";
	}

}
